/*
 * @Author: your name
 * @Date: 2020-05-06 12:17:11
 * @LastEditTime: 2020-07-09 10:36:11
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \truck\platform\common.c
 */
#include "global_common.h"


#ifndef _CORE_GETTID
#include <sys/syscall.h>
#define _CORE_GETTID()	syscall(SYS_gettid)
#endif


static void sig_reboot(int sig){
	PRTLOG_ERR("sysMgn Get signal %d",sig);
	if(sig == SIGTERM || sig == SIGKILL){
		// sysMgnt_exit();
	}
}
void sig_SIGSEGV(int signo)
{
	void *array[10];
	int size,i;
	char **strings;
	size = backtrace (array, 10);
	strings = backtrace_symbols (array, size);
	PRTLOG_ERR("sysMgn Get signal %d:Get %d stack frames.\n",signo,size);
	for (i = 0; i < size; i++)
		PRTLOG_ERR("%s\n", strings[i]);
	free (strings);
	// sysMgnt_exit();
}

void com_initSignals()
{
	 signal(SIGTERM,sig_reboot);
	 signal(SIGKILL,sig_reboot);
	 signal(SIGSEGV,sig_SIGSEGV);
}





int com_initXelog(){
	#if defined(CONFIG_USE_EXTERNAL_XELOG) && defined(XELOG_2_REMOTE)
	init_xelog_remote_t ilr;
	memset(&ilr,0,sizeof(ilr));
	#ifdef CONFIG_PLATFORM
	if ( !strcasecmp(CONFIG_PLATFORM, "HISI") ){
		ilr.log_level = 4;
		ilr.msg2stdout = 1;    
		ilr.msg2stderr = 0;
	}else{
		ilr.log_level = xeLOG_level_get();
		ilr.msg2stdout = 0;    
		ilr.msg2stderr = 0;
	}
	#else
	ilr.log_level = xeLOG_level_get();
	ilr.msg2stdout = 0;    
	ilr.msg2stderr = 0;
	#endif
	ilr.remotePort = 514; 
		strncpy(ilr.remoteIP,"127.0.0.1",sizeof(ilr.remoteIP)-1);
		return init_xelog_network(&ilr);
	#elif defined(CONFIG_USE_EXTERNAL_XELOG) && defined(XELOG_2_LOCAL)
		char *sysMgntlog="/home/log/sysMgnt";
		init_xelog_local_t ilr;
		memset(&ilr,0,sizeof(ilr));
		ilr.log_level = 7;
		ilr.num = 7;
		ilr.size = 1*1024*1024;
		ilr.local_port=0;
		sprintf(ilr.path,"%s",sysMgntlog);
		if(access(sysMgntlog,W_OK|R_OK) != 0){
			mkdir(sysMgntlog,0777);
    	}
		init_xelog_local(&ilr);
	#endif
	
	return 0;
}
int com_deInitXelog(){
	int rtl;
	#if defined(CONFIG_USE_EXTERNAL_XELOG) && defined(XELOG_2_REMOTE)
		rtl=deinit_xelog_network();
	#elif defined(CONFIG_USE_EXTERNAL_XELOG) && defined(XELOG_2_LOCAL)
		rtl=deinit_xelog_local();
	#endif
	return rtl;
	
}




typedef struct _cpuRateInfo{
   char name[32];
   unsigned int user;
   unsigned int nice;
   unsigned int sys;
   unsigned int idle;
}CPURateInfo;

typedef struct _memRateInfo{
   unsigned int total;
   unsigned int free;
   unsigned int avaliable;
}memRateInfo;

static int getProcessPidByName(const char *proc_name){
      FILE *fp;
      char buf[100];
      char cmd[200] = {'\0'};
      int pid = -1;
      sprintf(cmd, "pidof %s", proc_name);
      if((fp = popen(cmd, "r")) != NULL)
      {
          if(fgets(buf, 255, fp) != NULL)
          {
              pid = atoi(buf);
          }
      }
      pclose(fp);
      return pid;
}

static int getCpuInfo(char *file,CPURateInfo * info){
  FILE * fp=NULL;
  fp=fopen(file,"r");
  if(fp == NULL){
      printf("open %s fail\n",file);
      return -1;
  }else{
     char data[1024]={'\0'};
     fgets(data,1024,fp);
     sscanf(data,"%s %u %u %u %u",info->name,&info->user,&info->nice,&info->sys,&info->idle);
     fclose(fp);
  }
  return 0;
}

int com_getCPURate(){
	unsigned int rate=0;
	CPURateInfo info1,info2;
	memset(&info1,0,sizeof(CPURateInfo));
	memset(&info2,0,sizeof(CPURateInfo));
	getCpuInfo("/proc/stat",&info1);
	usleep(300000);
	getCpuInfo("/proc/stat",&info2);
	unsigned int total1=info1.user+info1.sys+info1.nice+info1.idle;   
	unsigned int total2=info2.user+info2.sys+info2.nice+info2.idle;
	unsigned int cha = (total2-info2.idle) -(total1-info1.idle);
	float shang = (cha*1.0)/(total2-total1);
	rate = (unsigned int)(100.0*shang);
	return rate;
}


/*
  process=NULL:memrate
  process != NULL:process use mem
*/
int com_getMemRate(char *process){
  unsigned int memRate=0;
  memRateInfo info;
  int pid=-1;
  char fname[512]={'\0'};
  if(process== NULL)
      sprintf(fname,"%s","/proc/meminfo");
  else{
     pid =getProcessPidByName(process);
     if(pid != -1){
       sprintf(fname,"/proc/%d/status",pid);
     }else{
       sprintf(fname,"FAIL");
     }
  }
  FILE * fp=NULL;
  if(strlen(fname)>5){
      fp=fopen(fname,"r");
      if(fp == NULL){
          printf("open %s fail\n",fname);
          return -1;
      }else{
        char data[1024]={'\0'};
        if(process == NULL){
          fgets(data,1024,fp);
          char name[128]={'\0'};
          char unit[128]={'\0'};
          sscanf(data,"%s %u %s",name,&info.total,unit);          
		  fgets(data,1024,fp);
          sscanf(data,"%s %u %s",name,&info.free,unit);
          info.free = info.free/1024;
          info.total = info.total/1024;
		  memRate = (unsigned int)((100.0)*(1-(1.0*info.free)/info.total));
        //   printf("MEM_Usage:%u\%\tDetail:free:%uMB  avaliable:%uMB  total:%uMB \n",(unsigned int)((100.0)*(1-(1.0*info.avaliable)/info.total)),info.free,info.avaliable,info.total); 
        }else{
          char name[128]={'\0'};
		  int i=0;
		  for(i=0;i<14;i++){
        		fgets (data, sizeof(data),fp);
           }//读到第15行
          fgets(data,1024,fp);
          sscanf(data,"%s %u",name,&memRate);
        //   printf("%s:\t%dMB\n",process,VmRss*4/1024);
        }
        fclose(fp);
      }
  }
  return memRate;
}

int com_getFanSpeed(){
	unsigned int speed=0;
	return speed;
}


int com_getCPUTemp(){
	unsigned int temp=40;
	return temp;
}

void com_fileCopy(const char *src,const char *dst){
	FILE * sp=NULL;
	FILE * dp=NULL;
	sp = fopen(src,"r");
	if(sp == NULL){
		PRTLOG_ERR("can not open %s",src);
	}else{
		dp = fopen(dst,"w");
		if(dp == NULL){
			PRTLOG_ERR("can not open %s",dst);
		}else{
			unsigned char data[1024]={'\0'};
			int len =0;
			do{
				len =fread(data,sizeof(char),sizeof(data),sp);
				if(len > 0){
					fwrite(data,sizeof(char),len,dp);	
				}
			}while(len >0);
			fclose(dp);
			fclose(sp);
			sync();
		}
	}
}


void com_httpPack(struct mg_connection *nc,cJSON *json){
	char * data = cJSON_Print(json);
	STD_print("respond data:%s",data);
	mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n");
	mg_printf_http_chunk(nc, "%s", data);
	free(data);
    mg_send_http_chunk(nc, "", 0); /* Send empty chunk, the end of response */            
}


 
void com_strtokSup(char * strlist){
	int n;
	int tmp_len = strlen(strlist);
	for(n=0;n<tmp_len; n++){
		if(strlist[0] == ','){ //第一个字符就是分隔符
			tmp_len++;
			int i;
			for(i=tmp_len; i>0; i--){
				strlist[i] = strlist[i-1];
			}
			strlist[0] = ' ';
		}
		if((strlist[n] == ',') && (strlist[n+1] == ',')){
			tmp_len++;
			int i;
			for(i=tmp_len; i>n; i--){
				strlist[i] = strlist[i-1];
			}
			strlist[n+1] = ' ';
		}
	}
	if(strlist[tmp_len-1]==','){
		strlist[tmp_len+1] = strlist[tmp_len];
		strlist[tmp_len] =  ' ';
	}
}

time_t com_localTimeStr2Int(const char * ts){
	struct tm t;
	sscanf(ts,"%04d-%02d-%02d %02d:%02d:%02d",&t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
	t.tm_year -= 1900;
	t.tm_mon -= 1;
 	return mktime(&t);
}


char * com_localTimeInt2Str(time_t ti,char *dst)
{
    struct tm *ot;
	memset(dst, 0 , sizeof(dst));
	//ot = gmtime(&t_int);
    ot = localtime(&ti);
    sprintf(dst,"%4d-%02d-%02d %02d:%02d:%02d",1900+ot->tm_year,1+ot->tm_mon,ot->tm_mday,ot->tm_hour,ot->tm_min,ot->tm_sec);
	return dst;
}

int com_pthread_mutex_lock(pthread_mutex_t *mutex,char *mutexName,const char * filename,int line){
	int mutextimes=0;
	//PRTLOG_ERR("%s try lock  %s .--called line:%d",filename,mutexName,line);
	while(0 != pthread_mutex_trylock(mutex)){
		usleep(50000);
		mutextimes++;
		if(mutextimes>=300){
			if(mutexName != NULL){
				PRTLOG_ERR("pthread_mutex_trylock  %s fail.--called line:%d",mutexName,line);
			}else{
				PRTLOG_ERR("pthread_mutex_trylock fail.--called line:%d",line);
			}
			return 1;
		}
	}
	return 0;
}

void com_pthread_mutex_unlock(pthread_mutex_t *mutex,char *mutexName,const char * filename,int line){
	//PRTLOG_ERR("%s try unlock  %s .--called line:%d",filename,mutexName,line);
	pthread_mutex_unlock(mutex);
}


long long get_file_size(const char *filename)  
{  
    long long size;  
    FILE* fp = fopen( filename, "rb" );  
    if(fp==NULL)  
    {  
        printf("ERROR: Open file %s failed.\n", filename);  
        return 0;  
    }  
    fseek( fp, SEEK_SET, SEEK_END );  
    size=ftell(fp);  
    fclose(fp);  
    return size;  
} 

void get_dir_name(char *file,char *dir_name)
{
	char *p =NULL;
	char *file_tmp = file;
	int size = 0;
	while((p = strstr(file_tmp,"/"))!=NULL){
		file_tmp =p+1;
	}
	size = file_tmp-file;
	memcpy(dir_name,file,size);
}
void get_file_name(char *file,char *file_name)
{
	char *p =NULL;
	char *file_tmp = file;
	int size = 0;
	while((p = strstr(file_tmp,"/"))!=NULL){
		file_tmp =p+1;
	}
	strcpy(file_name,file_tmp);
}

pthread_mutex_t uid_lock = PTHREAD_MUTEX_INITIALIZER;

int tiny_get_unique_id(int *id)
{
	int tmp_id;
	struct timespec uptime_time;
	pthread_mutex_lock(&uid_lock);
	usleep(1000);
	clock_gettime(CLOCK_MONOTONIC, &uptime_time);
	tmp_id = (int)(uptime_time.tv_sec);
	tmp_id = tmp_id*1000+uptime_time.tv_nsec/1000000;
	pthread_mutex_unlock(&uid_lock);
	*id = tmp_id;
	return 0;
}